﻿using System.Diagnostics;
using System.IO.Pipes;
using System.Text;
using Jupiter.Infrastructure;

namespace Wips.Infrastructure.Helpers
{
    public static class DiagnosticsHelper
    {
        public static string ExecuteCommand(string command)
        {
            var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
            {
                CreateNoWindow = true,
                UseShellExecute = false, // 必须设置为true才能使用"runas"动词
                //Verb = "runas", // 尝试以管理员权限运行
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.GetEncoding("GB2312"),
                StandardErrorEncoding = Encoding.GetEncoding("GB2312")
            };

            var process = Process.Start(processInfo);
            try
            {
                string output = process!.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();

                if (process.ExitCode == 0)
                {

                    return output;
                }
                else
                {
                    throw new Exception("[" + process.ExitCode + "]" + output + error);
                }

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                process!.Close();
            }




        }

        public static string ExecuteCommandWithRunas(string command)
        {
            var file = ObjectId.GenerateNewId().ToString(); ;
            string outputFile = @".\" + file + ".txt"; // 替换为你的输出文件路径

            // 创建一个命名管道客户端
            using (var client = new NamedPipeClientStream("InheartAgentBackServer"))
            {
                // 连接到服务器
                client.Connect();

                // 发送一个CMD命令
                using (var writer = new StreamWriter(client))
                {
                    writer.Write(command + " " + outputFile);
                    writer.Flush();
                }
            }

            string output = File.ReadAllText(outputFile);
            return output;

        }
    }
}
